package io.chenhd.gateway.client;

import io.chenhd.gateway.cache.ConnectCache;
import io.chenhd.gateway.cache.ContextCache;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import java.net.URI;

public class NettyHttpClient {


    public static Channel connect(ChannelHandlerContext ctx, String url) throws Exception {
        try {
            URI uri = new URI(url);
            String ipPort = uri.getHost() + "_" + uri.getPort();
            Channel channel = ConnectCache.getChannel(ipPort);
            DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.GET, url);
            ContextCache.clientCache.put(ctx, channel);
            channel.writeAndFlush(httpRequest).sync();
//            channel.closeFuture().sync();
            return channel;
        } finally {
//            workerGroup.shutdownGracefully();
        }

    }

}